<template>
  <el-dialog title="物料/产品选择" v-if="showFlag" :visible.sync="showFlag"
             :close-on-click-modal="false" :modal=false width="75%" height="95%" center>
    <el-row :gutter="20">
      <!--分类数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="itemTypeName" placeholder="请输入分类名称" clearable size="small" prefix-icon="el-icon-search"
                    style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="itemTypeOptions" :props="defaultProps" :expand-on-click-node="false"
                   :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--物料数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="物料/产品编码" prop="itemCode" label-width="120">
            <el-input v-model="queryParams.itemCode" placeholder="请输入编码" clearable style="width: 240px"
                      @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="物料/产品名称" prop="itemName" label-width="120">
            <el-input v-model="queryParams.itemName" placeholder="请输入名称" clearable style="width: 240px"
                      @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button type="primary" icon="el-icon-add" size="mini" @click="addRow">新增物料/产品</el-button>
          </el-form-item>
        </el-form>

        <div class="table-container">
          <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange" highlight-current-row
                    @current-change="handleCurrent" style="overflow: auto;">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column type="index" width="50">
          </el-table-column>
          <el-table-column label="物料/产品编码" align="left" prop="itemCode"
                           v-if="columns[0].visible">
            <template slot-scope="scope">
              <el-input align="center" type="text" v-model="scope.row.itemCode" v-show="scope.row.isEditor"/>
              <span v-show="!scope.row.isEditor">{{ scope.row.itemCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料/产品名称" align="left" prop="itemName"
                           v-if="columns[1].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-input align="center" type="text" v-model="scope.row.itemName" v-show="scope.row.isEditor"/>
              <span v-show="!scope.row.isEditor">{{ scope.row.itemName }}</span>
            </template>
          </el-table-column>

<!--          <el-table-column label="物料图片" align="left" prop="imgUrl" width="80">
              <template slot-scope="scope">
                &lt;!&ndash; 图片预览 &ndash;&gt;
                <div v-if="scope.row.imgUrl" class="image-container">
                  <image-preview :src="scope.row.imgUrl" :width="50" :height="50"/>
                </div>
                &lt;!&ndash; 上传图标 &ndash;&gt;
                <div v-else class="avatar-uploader image-container">
                  <image-upload
                      v-model="scope.row.imgUrl"
                      :limit="1"
                      @input="(newValue) => scope.row.imgUrl = newValue">
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                  </image-upload>
                </div>
              </template>
            </el-table-column>-->

          <el-table-column label="物料图片" align="left" prop="imgUrl" width="80">
            <template slot-scope="scope">
              <!-- 图片预览 -->
              <div v-if="scope.row.imgUrl" class="image-container">
                <image-preview :src="scope.row.imgUrl" :width="50" :height="50"/>
              </div>
              <!-- 上传图标 -->
              <div v-else class="avatar-uploader image-container">
                <image-upload
                    v-model="scope.row.imgUrl"
                    :limit="1"
                    @input="(newValue) => scope.row.imgUrl = newValue">
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                </image-upload>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="类型" align="center" prop="itemOrProduct" width="80">
<!--            <template slot-scope="scope">
              <el-tag :type="scope.row.itemOrProduct === 'product' ? 'success' : 'primary'">
                {{ scope.row.itemOrProduct === 'product' ? '产品' : '物料' }}
              </el-tag>
            </template>-->
            <template slot-scope="scope">
              <el-tag :type="(scope.row.itemOrProduct || '').toLowerCase() === 'product' ? 'success' : 'primary'">
                {{ (scope.row.itemOrProduct || '').toLowerCase() === 'product' ? '产品' : '物料' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" align="left" prop="specification" v-if="columns[2].visible"
                           :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-input align="center" type="text" v-model="scope.row.specification" v-show="scope.row.isEditor"/>
              <span v-show="!scope.row.isEditor">{{ scope.row.specification }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="left" prop="unitOfMeasure" v-if="columns[3].visible"
                           :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-select size="mini" v-model="scope.row.unitOfMeasure" placeholder="请选择单位"
                         v-show="scope.row.isEditor">
                <el-option v-for="item in measureOptions" :key="item.measureCode" :label="item.measureName"
                           :value="item.measureCode" :disabled="item.enableFlag == 'N'"></el-option>
              </el-select>
              <el-select class="no-border-select" size="mini" disabled v-model="scope.row.unitOfMeasure"
                         placeholder="请选择单位" v-show="!scope.row.isEditor">
                <el-option v-for="item in measureOptions" :key="item.measureCode" :label="item.measureName"
                           :value="item.measureCode" :disabled="item.enableFlag == 'N'"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物料分类" align="left" prop="itemTypeName" v-if="columns[5].visible"
                           :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <treeselect v-model="scope.row.itemTypeId" :options="itemTypeOptions" :show-count="true"
                          placeholder="请选择分类" v-show="scope.row.isEditor" :disable-branch-nodes="true"/>
              <span v-show="!scope.row.isEditor">{{ scope.row.itemTypeName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240" align="center">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-edit" @click="edit(scope.row)"
                         v-show="!scope.row.isEditor">编辑
              </el-button>
              <el-button type="text" icon="el-icon-delete" @click="del(scope.row)"
                         v-show="!scope.row.isEditor">删除
              </el-button>
              <el-button type="text" icon="el-icon-add" @click="save(scope.row)"
                         v-show="scope.row.isEditor">保存
              </el-button>
              <el-button type="text" icon="el-icon-add" @click="cancel(scope.row)"
                         v-show="scope.row.isEditor">取消
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList"/>
      </div>
    </el-col>
    </el-row>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="confirmSelect">确 定</el-button>
      <el-button @click="confirmCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {listMdItemProduct,listMdItem, getMdItem, delMdItem, addItemProduct, updateMdItem} from "@/api/mes/md/mdItem";
import {listItemType, treeselect} from "@/api/mes/md/itemtype";
import {genCode} from "@/api/system/autocode/rule"
import {mapGetters} from "vuex";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "MdItemSingle",
  dicts: ['sys_yes_no', 'mes_item_product'],
  components: {Treeselect},
  props: {
    itemOrProduct: {
      type: String,
      default: 'product',
      multiFlag: ''
    }
  },
  computed: {
    ...mapGetters({
      measureOptions: 'unitmeasureList'
    })
  },
  data() {
    return {
      showFlag: false,
      // 选中数组
      selectedItemId: [],
      selectedRows: [],
      currentRow: undefined,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料产品表格数据
      itemList: null,
      // 部门树选项
      itemTypeOptions: undefined,
      // 部门名称
      itemTypeName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      btnDisabled: false,
      // 当前选中的分类
      currentSelectedCategory: null,
      currentSelectItemOrProduct:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemCode: undefined,
        itemName: undefined,
        itemTypeId: 0,
        multiFlag: this.multiFlag,
        itemOrProduct: undefined // 不限制物料或产品类型
      },
      // 列信息
      columns: [
        {key: 0, label: `产品编码`, visible: true},
        {key: 1, label: `产品名称`, visible: true},
        {key: 2, label: `规格型号`, visible: true},
        {key: 3, label: `单位`, visible: true},
        {key: 4, label: `物料/产品`, visible: true},
        {key: 5, label: `物料分类`, visible: true},
        {key: 6, label: `创建时间`, visible: true}
      ]
    };
  },
  watch: {
    // 根据名称筛选分类树
    itemTypeName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    // 移除自动API调用，只在show()方法中调用
    this.btnDisabled = false;
  },
  methods: {
    /** 显示弹窗 */
    show() {
      this.showFlag = true;
      this.btnDisabled = false;
      // 在显示对话框时加载数据
      this.getList();
      this.getTreeselect();
    },
    /** 查询物料编码列表 */
    getList() {
      this.loading = true;
      // 修改查询参数，获取所有物料和产品
      const queryParams = {
        ...this.queryParams,
        itemOrProduct: undefined // 不限制类型，获取所有
      };
      listMdItem(queryParams).then(response => {
        this.itemList = response.rows;
        this.itemList.forEach(element => {
          this.$set(element, 'isEditor', false)
        });
        this.total = response.total;
        this.loading = false;
      });

    },
    /** 查询分类下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        console.log('treeSelect--',response.data);
        this.itemTypeOptions = response.data;
      });
    },
    addRow() {
      let editList = this.itemList.filter(item => {
        return item.isEditor === true
      });
      if (editList.length !== 0) {
        this.$notify({
          title: '提示',
          type: 'warning',
          message: '每次只能修改一条数据,请保存后再添加'
        });
        return;
      }

      // 获取当前选中的分类
      let selectedItemType = this.getCurrentSelectedCategory();
      if (!selectedItemType) {
        this.$notify({
          title: '提示',
          type: 'warning',
          message: '请先选择一个分类'
        });
        return;
      }

      // 获取分类的 itemOrProduct 类型
      const itemType = this.getItemTypeByCategory(selectedItemType);

      const confirmMessage = `将添加${itemType === 'PRODUCT' ? '产品' : '物料'}\n当前选中分类：${selectedItemType.label}`;

      this.$confirm(confirmMessage, '确认添加', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.addNewItem(itemType);
      }).catch(() => {
        // 用户取消操作
      });
    },
    addNewItem(type) {
      console.log('addNewItem type----',type);
      this.btnDisabled = true;
      // let codeType = type === 'product' ? 'PRODUCT_CODE' : 'ITEM_CODE';
      let codeType = (type || '').toLowerCase() === 'product'
          ? 'PRODUCT_CODE'
          : 'ITEM_CODE';
      genCode(codeType).then(response => {
        // 获取当前选中的分类信息
        let selectedItemType = this.getCurrentSelectedCategory();

        var row = {
          itemId: undefined,
          itemCode: response,
          itemName: undefined,
          specification: undefined,
          unitOfMeasure: undefined,
          itemOrProduct: type, // 使用传入的 type（由分类决定）
          itemTypeId: selectedItemType ? selectedItemType.id : undefined,
          itemTypeName: selectedItemType ? selectedItemType.label : undefined,
          createTime: undefined,
          createBy: undefined,
          updateTime: undefined,
          updateBy: undefined,
          remark: undefined,
          isEditor: true
        };
        this.itemList.push(row);
        this.btnDisabled = false;
      }).catch(() => {
        this.btnDisabled = false;
      });
    },
    save(row) {
      console.log('保存：{}',row);
      if (row.itemId === undefined) {
        // 新增时根据类型调用不同的API
        addItemProduct(row, row.itemOrProduct).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.getList();
          this.btnDisabled = false;
        });
      } else {
        updateMdItem(row).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.getList();
          this.btnDisabled = false;
        });
      }
    },
    edit(row) {
      row.isEditor = true;
    },
    del(row) {
      this.$modal.confirm('确认删除数据项？').then(function () {
        return delMdItem(row.itemId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    cancel(row) {
      let editList = this.itemList.filter(item => {
        return item.isEditor === true
      });
      if (editList.length > 0) {
        this.$confirm('有未保存的数据,确定取消吗', "提示", {confirmButtonText: '确定', type: 'info'})
            .then(() => {
              this.btnDisabled = false;
              row.isEditor = false;
            }).catch(() => {
              // 用户取消操作，保持当前状态
            });
      } else {
        // 没有编辑中的数据，直接重置状态
        this.btnDisabled = false;
        row.isEditor = false;
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.itemTypeId = data.id;
      this.currentSelectedCategory = data; // 更新当前选中的分类
      console.log('单击节点:',data);
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.itemTypeId = 0;
      this.queryParams.itemOrProduct = undefined; // 不限制类型
      this.currentSelectedCategory = null; // 清空当前选中的分类
      this.handleQuery();
    },
    handleCurrent(row) {
      if (row === undefined || row === null) {
        return;
      }
      this.currentRow = row;
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      this.selectedItemId = selection.map(item => item.itemId);
    },
    handleRowDbClick(row) {
      if (row === undefined || row.itemId === undefined) {
        this.$notify({
          title: '提示',
          type: 'warning',
          message: '所选数据不符合规则,请重新选择!'
        });
        return;
      }
      this.currentRow = row;
      this.$emit('onSelected', [row]);
      this.clearEmptyData();
      this.showFlag = false;
    },
    // 单选选中数据
    handleRowChange(row) {
      if (row) {
        this.currentRow = row;
      }
    },
    //确定选中
    confirmSelect() {
      if (this.selectedRows === undefined || this.selectedRows.length === 0) {
        this.$notify({
          title: '提示',
          type: 'warning',
          message: '请至少选择一条数据!'
        });
        return;
      }
      this.$emit('onSelected', this.selectedRows);
      this.clearEmptyData();
      this.showFlag = false;
      this.btnDisabled = false;
    },
    /** 取消按钮 */
    confirmCancel() {
      this.clearEmptyData();
      this.showFlag = false;
      this.btnDisabled = false;
    },
    /** 清理表格中的空数据 */
    clearEmptyData() {
      let rows = this.itemList.filter(item => {
        return item.itemId !== undefined && item.itemId !== '' && item.itemId !== null;
      });
      this.itemList = rows;
      // 清理数据后重置按钮状态
      this.btnDisabled = false;
    },
    // 辅助方法：根据ID查找树节点
    findItemTypeById(id, options) {
      for (let i = 0; i < options.length; i++) {
        if (options[i].id === id) {
          return options[i];
        }
        if (options[i].children) {
          const found = this.findItemTypeById(id, options[i].children);
          if (found) {
            return found;
          }
        }
      }
      return null;
    },


    getItemTypeByCategory(category) {
      if (!category) return 'ITEM'; // 默认为物料，大写

      // 优先使用分类节点上的 itemOrProduct 字段
      if (category.itemOrProduct) {
        // 统一转为小写后判断
        const type = category.itemOrProduct.toLowerCase();
        if (type === 'product') {
          return 'PRODUCT'; // 返回大写
        } else if (type === 'item') {
          return 'ITEM'; // 返回大写
        }
      }
      // 如果没有 itemOrProduct 字段，默认为物料（大写）
      return 'ITEM';
    },


    getCurrentSelectedCategory() {
      if (this.currentSelectedCategory) {
        return this.currentSelectedCategory;
      }

      if (this.queryParams.itemTypeId && this.queryParams.itemTypeId !== 0) {
        return this.findItemTypeById(this.queryParams.itemTypeId, this.itemTypeOptions);
      }

      if (this.$refs.tree) {
        const currentNode = this.$refs.tree.getCurrentNode();
        if (currentNode) {
          return currentNode;
        }
      }
      return null;
    }
  }
};
</script>

<style scoped>
.el-dialog {
  margin-top: 8vh !important;
}

.el-dialog__body {
  max-height: 70vh;
  overflow: auto; /* 改为auto，同时支持水平和垂直滚动 */
  padding: 10px;
}

.el-table {
  max-height: 45vh;
  overflow: auto; /* 表格也支持滚动 */
}

.head-container {
  max-height: 45vh;
  overflow: auto; /* 分类树也支持滚动 */
}

/* 确保表格容器支持水平滚动 */
.el-table__body-wrapper {
  overflow: auto;
}

/* 确保弹窗内容区域支持滚动 */
.el-dialog__body {
  overflow-x: auto;
  overflow-y: auto;
}

/* 表格列的最小宽度，防止内容挤压 */
.el-table .el-table__cell {
  min-width: 100px;
}

/* 确保表格头部也支持水平滚动 */
.el-table__header-wrapper {
  overflow: hidden;
}

/* 表格容器样式 */
.table-container {
  max-height: 50vh;
  overflow: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

/* 确保表格在容器内正确显示 */
.table-container .el-table {
  max-height: none;
}

/* 优化滚动条样式 */
.el-dialog__body::-webkit-scrollbar,
.table-container::-webkit-scrollbar,
.head-container::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.el-dialog__body::-webkit-scrollbar-thumb,
.table-container::-webkit-scrollbar-thumb,
.head-container::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 4px;
}

.el-dialog__body::-webkit-scrollbar-track,
.table-container::-webkit-scrollbar-track,
.head-container::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}



/* 确保容器有一个固定大小，并且内容居中 */
.image-container {
  width: 50px; /* 调整为你希望的宽度 */
  height: 50px; /* 调整为你希望的高度 */
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 自定义上传区域的样式 */
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 50px; /* 宽度占满父容器 */
  height: 50px; /* 高度占满父容器 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

/* 设置加号图标的大小并确保其居中 */
.avatar-uploader-icon {
  font-size: 24px; /* 根据需要调整大小 */
  color: #8c939d;
  line-height:40px; /* 和容器高度一致，确保垂直居中 */
}
.avatar-uploader {
  background-color: #fbfdff; /* 可选：提供一个轻柔的背景色 */
  transition: border-color .2s cubic-bezier(.645,.045,.355,1);
}



</style>
